package net.mikoo.seals.manage.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.mikoo.seals.biz.service.CompanyService;
import net.mikoo.seals.biz.service.OrganizationService;
import net.mikoo.seals.biz.service.PartyServices;
import net.mikoo.seals.biz.service.StaffServices;
import net.mikoo.seals.biz.service.WorkflowService;
import net.mikoo.seals.common.WebContext;
import net.mikoo.seals.common.exception.ParametersException;
import net.mikoo.seals.manage.web.common.BaseController;
import net.mikoo.seals.model.Company;
import net.mikoo.seals.model.CompanyQuery;
import net.mikoo.seals.model.Party;
import net.mikoo.seals.model.PartyQuery;
import net.mikoo.seals.model.Workflow;
import net.mikoo.seals.model.WorkflowQuery;
import net.mikoo.seals.model.WorkflowSetting;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/company")
public class CompanyController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(CompanyController.class);

	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private PartyServices partyServices;
	
	@Autowired
	private OrganizationService organizationService;
	
	@Autowired
	private StaffServices staffServices;
	
	@Autowired
	private WorkflowService workflowService;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	/**
	 * 公司信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/info")
	public String info(CompanyQuery query,HttpServletRequest request,Model model){
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			
			query.setCompanyId(companyId);
			Company company = companyService.getInfoByQuery(query);
			
			Integer staffTotal = staffServices.getTotal(companyId);
			Integer orgTotal = organizationService.getTotal(companyId);
			
			model.addAttribute("company", company);
			model.addAttribute("staffTotal", staffTotal);
			model.addAttribute("orgTotal", orgTotal);
			model.addAttribute("query", query);
			return "/company/info";
	}
	
	/**
	 * 公司权限
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/role")
	public String role(HttpServletRequest request,Model model){
			
			Company company = getCompany(request);
			
			PartyQuery partyQuery = new PartyQuery();
			partyQuery.setIsSystem("Y");
			partyQuery.setPartyId(company.getPartyId());
			
			Party admin = partyServices.getInfoByQuery(partyQuery);
			model.addAttribute("admin", admin);
			
//			CustosQuery query = new CustosQuery();
//			query.setCompanyId(company.getCompanyId());
//			List<Custos> custoses = custosService.getListByQuery(query);
//			model.addAttribute("custoses", custoses);
			
			
			return "/company/role";
	}
	
	
	@RequestMapping("/edit")
	public String edit(Company company,HttpServletRequest request,Model model){
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		company.setCompanyId(companyId);
		model.addAttribute("company", company);
		return "/company/edit";
	}
	
	
	@RequestMapping("/modify")
	@ResponseBody
	public Map<String,Object> modify(Company company,HttpServletRequest request,Model model){
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		company.setCompanyId(companyId);
		
		try {
			companyService.modify(company);
			return result(SUCCESS, MSG_SUCCESS);
		}catch (ParametersException e) {
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
	}
	
	@RequestMapping("/transfer")
	public String transfer(HttpServletRequest request,Model model){
		
		Party party = getParty(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		model.addAttribute("party", party);
		return "/company/transfer";
	}
	
	@RequestMapping("/transfer/submit")
	@ResponseBody
	public Map<String,Object> transferSubmit(Long toPartyId,String smsCode,HttpServletRequest request,Model model){
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		Party party = getParty(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		try {
			if(toPartyId == null) {
				throw new ParametersException("请选择系统管理接收人");
			}
			
			if(StringUtils.isBlank(smsCode)) {
				throw new ParametersException("请输入短信验证码");
			}
			
			String code = redisTemplate.opsForValue().get("sms_send_code_"+party.getUserLoginId());
			if(StringUtils.isBlank(code) || !code.equals(smsCode)) {
				throw new ParametersException("短信验证码输入错误");
			}
		
			companyService.transferAdmin(companyId,party.getPartyId(),toPartyId);
			removeSession(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			return result(SUCCESS, MSG_SUCCESS);
		}catch (ParametersException e) {
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
	}
	
	
	@RequestMapping("/workflows")
	public String workflows(WorkflowQuery query, HttpServletRequest request, Model model) {
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		query.setCompanyId(companyId);
		List<Workflow> workflows = workflowService.getListByQuery(query);
		model.addAttribute("workflows", workflows);
		model.addAttribute("query", query);
		
		return "/company/workflows";
	}
	
	@RequestMapping("/workflow/add")
	public String workflowAdd() {
		
		
		return "/company/workflowAdd";
	}
	
	@RequestMapping("/workflow/create")
	@ResponseBody
	public Map<String, Object> workflowCreate(Workflow workflow, HttpServletRequest request){
		try {
			
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			
			workflow.setCompanyId(companyId);
			
			workflowService.create(workflow);
			
			return result(SUCCESS, "添加成功");
		}catch(ParametersException pe) {
			logger.error("", pe);
			return result(ERROR, pe.getMessage());
		}catch(Exception e) {
			logger.error("系统错误", e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
	}
	
	
	@RequestMapping("/workflow/update")
	public String update(WorkflowQuery query, Model model,HttpServletRequest request) {
		
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		query.setCompanyId(companyId);
		List<Workflow> workflows = workflowService.getListByQuery(query);
		model.addAttribute("workflows", workflows);
		model.addAttribute("query", query);
		
		Workflow workflow = workflowService.getInfoById(query.getWorkflowId());
		model.addAttribute("workflow", workflow);
		if(workflow!= null) {
			List<WorkflowSetting> settings = workflowService.getSettingsByWorkflowId(workflow.getWorkflowId());
			model.addAttribute("settings", settings);
			
			JSONArray array = new JSONArray();
			for (WorkflowSetting setting : settings) {
				JSONObject obj = new JSONObject();
				obj.put("name", setting.getPerson().getName());
				obj.put("portrait", setting.getPerson().getPortrait());
				obj.put("position", "");
				obj.put("id", setting.getPerson().getPartyId());
				array.add(obj);
			}
			model.addAttribute("settingsDatas", array.toString());
			
		}
		
		
		return "/company/workflows";

	}
	
	@RequestMapping("/modify")
	@ResponseBody
	public Map<String, Object> modify(Workflow workflow, HttpServletRequest request){
		try {
			
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			workflow.setCompanyId(companyId);
			
			workflowService.modify(workflow);
			return result(SUCCESS, "设置成功");
		}catch(ParametersException pe) {
			logger.error("", pe);
			return result(ERROR, pe.getMessage());
		}catch(Exception e) {
			logger.error("系统错误", e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
	}
	
	
}
